import 'dart:developer';

/// 输出Log工具类
class Log {
  static const String _defTag = 'hk_log';
  static bool _debugMode = true; //是否是debug模式,true: log v 不输出.
  static int _maxLen = 128;
  static String _tagValue = _defTag;

  /// 所在文件名
  static String _fileName = "";

  /// 所在行
  static int _lineNumber = 0;
  static int _columnNumber = 0;

  static Future<void> init({
    String tag = _defTag,
    bool isDebug = true,
    int maxLen = 512,
  }) async {
    _tagValue = tag;
    _debugMode = isDebug;
    _maxLen = maxLen;
  }

  static Future<void> d(
      Object? object, {
        String? tag = _defTag,
        StackTrace? trace,
      }) async {
    trace ??= StackTrace.current;
    var traceString = trace.toString().split("\n")[0];
    var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z_]+.dart'));
    var fileInfo = traceString.substring(indexOfFileName);
    var listOfInflows = fileInfo.split(":");
    _fileName = listOfInflows[0];
    _lineNumber = int.parse(listOfInflows[1]);
    var columnStr = listOfInflows[2];
    columnStr = columnStr.replaceFirst(")", "");
    _columnNumber = int.parse(columnStr);

    if (_debugMode) {
      if (_fileName.isNotEmpty &&
          _fileName != "hk_log.dart" &&
          _lineNumber != 0) {
        log('$tag d \n 所在文件名: $_fileName, 所在行: $_lineNumber 行,\n 打印信息: ${object?.toString()}');
      } else {
        log("打印信息:${object?.toString()}");
      }
    }
  }

  static void e(Object? object, {String? tag}) {
    _printLog(tag, ' e ', object);
  }

  static void v(Object? object, {String? tag}) {
    if (_debugMode) {
      _printLog(tag, ' v ', object);
    }
  }

  static void _printLog(String? tag, String stag, Object? object) {
    String da = object?.toString() ?? 'null';
    tag = tag ?? _tagValue;
    if (da.length <= _maxLen) {
      print('$tag$stag $da');
      return;
    }
    print(
        '$tag$stag — — — — — — — — — — — — — — — — st — — — — — — — — — — — — — — — —');
    while (da.isNotEmpty) {
      if (da.length > _maxLen) {
        print('$tag$stag| ${da.substring(0, _maxLen)}');
        da = da.substring(_maxLen, da.length);
      } else {
        print('$tag$stag| $da');
        da = '';
      }
    }
    print(
        '$tag$stag — — — — — — — — — — — — — — — — ed — — — — — — — — — — — — — — — —');
  }
}